<template>
	<view class="edit-address-container">
		<!-- 头部区域 -->
		<headerSlotVue :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header-content" @click="closePage()">
					<view class="header-left">
						<view class="back-btn">
							<text class="back-icon">←</text>
						</view>
					</view>
					<view class="header-center">
						<text class="page-title">{{title}}</text>
					</view>
					<view class="header-right">
						<view class="header-actions">
							<text class="action-text">保存</text>
						</view>
					</view>
				</view>
			</template>
		</headerSlotVue>

		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 表单卡片 -->
			<view class="form-card">
				<uni-forms ref="form" :modelValue="formData" border :rules="rulesForm" validate-trigger="submit">
					<!-- 默认地址设置 -->
					<uni-forms-item label="设为默认" name="isDefault">
						<view class="switch-container">
							<switch 
								class="custom-switch" 
								@change="SwitchChange" 
								:checked="formData.isDefault"
								color="#FF6B35"
							></switch>
							<text class="switch-label">设为默认收货地址</text>
						</view>
					</uni-forms-item>
					
					<!-- 收货人信息 -->
					<uni-forms-item label="收货人" name="receiver">
						<uni-easyinput 
							type="text" 
							v-model="formData.receiver" 
							:inputBorder="false"
							placeholder="请输入收货人姓名" 
							class="custom-input"
						/>
					</uni-forms-item>
					
					<!-- 手机号码 -->
					<uni-forms-item label="手机号" name="phone">
						<uni-easyinput 
							type="text" 
							v-model="formData.phone" 
							:inputBorder="false" 
							placeholder="请输入收货人联系电话" 
							class="custom-input"
						/>
					</uni-forms-item>
					
					<!-- 地区选择 -->
					<uni-forms-item label="地区" name="province">
						<sh-address @change="change" v-model="addressInfo" class="address-picker"></sh-address>
					</uni-forms-item>
					
					<!-- 详细地址 -->
					<uni-forms-item label="详细地址" name="detail">
						<uni-easyinput 
							type="textarea" 
							maxlength="-1" 
							:inputBorder="false" 
							placeholder="街道、门牌号等地址信息"
							v-model="formData.detail"
							class="custom-textarea"
						></uni-easyinput>
					</uni-forms-item>
				</uni-forms>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="bottom-actions">
			<view class="action-buttons">
				<button 
					v-if="title=='编辑地址'" 
					class="delete-btn" 
					@click="deleteAddress"
				>
					<text class="btn-text">删除地址</text>
				</button>
				<button class="save-btn" @click="submitFrorm" :disabled="isSubmitting">
					<text class="btn-text">{{ isSubmitting ? '保存中...' : '保存地址' }}</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import headerSlotVue from '@/components/header-slot.vue';
	import {
		addUserAddress,
		updateUserAddress,
		deleteAddressInfo
	} from '@/api/mine';
	
	export default {
		components: {
			headerSlotVue,
		},
		data() {
			return {
				formData: {
					receiver: '',
					phone: '',
					province: '',
					city: '',
					district: '',
					detail: '',
					isDefault: false,
				},
				title: '添加地址',
				addressInfo: [],
				rulesForm: {
					receiver: {
						rules: [{
							required: true,
							errorMessage: '请填写收货人',
						}],
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '请填写联系电话',
						}, {
							validateFunction: function(rule, value, data, callback) {
								let iphoneReg = /^1[0-9]{10}$/
								if (!iphoneReg.test(value)) {
									callback('手机号码格式不正确，请重新填写')
								}
								return true
							}
						}]
					},
					province: {
						rules: [{
							required: true,
							errorMessage: '请选择省市区',
						}],
					},
					city: {
						rules: [{
							required: true,
							errorMessage: '请选择省市区',
						}],
					},
					district: {
						rules: [{
							required: true,
							errorMessage: '请选择省市区',
						}],
					},
					detail: {
						rules: [{
							required: true,
							errorMessage: '请填写详细地址',
						}],
					},
				},
				// 添加防抖相关状态
				isSubmitting: false,
				submitTimer: null
			};
		},
		onLoad(opt) {
			if (opt.type === 'edit') {
				this.title = '编辑地址'
				this.formData = uni.getStorageSync('address')
				this.addressInfo[0] = this.formData.province
				this.addressInfo[1] = this.formData.city
				this.addressInfo[2] = this.formData.district
			} else {
				this.title = '添加地址'
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rulesForm)
		},
		methods: {
			SwitchChange(e) {
				this.formData.isDefault = e.detail.value
			},
			change(addressInfo) {
				this.formData.province = addressInfo.province
				this.formData.city = addressInfo.city
				this.formData.district = addressInfo.area
			},
			deleteAddress() {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个地址吗？',
					success: (res) => {
						if (res.confirm) {
							deleteAddressInfo(this.formData._id).then(res => {
								if (res.data.code === 200) {
									uni.showToast({
										title: "删除成功",
										icon: "success",
									});
									this.closePage()
								} else {
									uni.showToast({
										title: "删除地址失败",
										icon: "error",
									});
								}
							}).catch(err => {
								uni.showToast({
									title: "删除地址失败",
									icon: "error",
								});
							})
						}
					}
				})
			},
			submitFrorm() {
				// 防抖处理：如果正在提交中，直接返回
				if (this.isSubmitting) {
					uni.showToast({
						title: "正在保存中，请稍候...",
						icon: "none",
					});
					return;
				}

				// 清除之前的定时器
				if (this.submitTimer) {
					clearTimeout(this.submitTimer);
				}

				// 设置防抖延迟
				this.submitTimer = setTimeout(() => {
					this.performSubmit();
				}, 300);
			},

			// 实际执行提交的方法
			performSubmit() {
				this.$refs.form.validate().then(() => {
					// 设置提交状态
					this.isSubmitting = true;
					
					uni.showLoading({
						mask: true,
						title: '保存中...'
					})

					if (this.title === '编辑地址') {
						updateUserAddress({
							id: this.formData._id,
							data: this.formData
						}).then(res => {
							if (res.data.code === 200) {
								uni.hideLoading()
								uni.showToast({
									title: "修改成功",
									icon: "success",
								});
								this.closePage()
							} else {
								uni.hideLoading()
								uni.showToast({
									title: "修改地址失败",
									icon: "error",
								});
							}
						}).catch(err => {
							uni.hideLoading()
							uni.showToast({
								title: "修改地址失败",
								icon: "error",
							});
						}).finally(() => {
							this.isSubmitting = false;
						})
						return
					}
					
					addUserAddress(this.formData).then(res => {
						if (res.data.code === 200) {
							uni.hideLoading()
							uni.showToast({
								title: "添加成功",
								icon: "success",
							});
							this.closePage()
						} else {
							uni.hideLoading()
							uni.showToast({
								title: "新增地址失败",
								icon: "error",
							});
						}
					}).catch(err => {
						uni.hideLoading()
						uni.showToast({
							title: "新增地址失败",
							icon: "error",
						});
					}).finally(() => {
						this.isSubmitting = false;
					})
				}).catch((err) => {
					uni.showToast({
						title: "请完善地址信息",
						icon: "error",
					});
					this.isSubmitting = false;
				})
			},
			closePage() {
				uni.navigateBack()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.edit-address-container {
		background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
		min-height: 100vh;
	}

	// 头部样式
	.header-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		width: 100%;
		
		.header-left {
			.back-btn {
				width: 64rpx;
				height: 64rpx;
				background: rgba(255, 255, 255, 0.9);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
				transition: all 0.3s ease;
				
				&:active {
					transform: scale(0.95);
					background: rgba(255, 255, 255, 1);
				}
				
				.back-icon {
					font-size: 32rpx;
					color: #333;
					font-weight: 600;
				}
			}
		}
		
		.header-center {
			flex: 1;
			text-align: center;
			
			.page-title {
				font-size: 36rpx;
				font-weight: 700;
				color: #333;
			}
		}
		
		.header-right {
			.header-actions {
				.action-text {
					font-size: 24rpx;
					color: #666;
					background: rgba(255, 255, 255, 0.8);
					padding: 8rpx 16rpx;
					border-radius: 20rpx;
				}
			}
		}
	}

	// 主要内容区域
	.main-content {
		padding: 32rpx;
		padding-bottom: 160rpx;
	}

	// 表单卡片
	.form-card {
		background: white;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		
		// 自定义开关样式
		.switch-container {
			display: flex;
			align-items: center;
			gap: 16rpx;
			
			.custom-switch {
				transform: scale(0.8);
			}
			
			.switch-label {
				font-size: 28rpx;
				color: #666;
			}
		}
		
		// 自定义输入框样式
		.custom-input {
			:deep(.uni-easyinput__content) {
				background: #f8f9fa;
				border-radius: 12rpx;
				padding: 8rpx 16rpx;
			}
			
			:deep(.uni-easyinput__content-input) {
				font-size: 28rpx;
				color: #333;
			}
		}
		
		// 自定义文本域样式
		.custom-textarea {
			:deep(.uni-easyinput__content) {
				background: #f8f9fa;
				border-radius: 12rpx;
				padding: 16rpx;
				min-height: 120rpx;
			}
			
			:deep(.uni-easyinput__content-textarea) {
				font-size: 28rpx;
				color: #333;
				line-height: 1.5;
			}
		}
		
		// 地址选择器样式
		.address-picker {
			:deep(.uni-data-picker) {
				background: #f8f9fa;
				border-radius: 12rpx;
				padding: 8rpx 16rpx;
			}
		}
	}

	// 底部操作按钮
	.bottom-actions {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 32rpx;
		background: white;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
		
		.action-buttons {
			display: flex;
			gap: 24rpx;
			
			.delete-btn {
				flex: 1;
				height: 100rpx;
				background: white;
				border: 2rpx solid #FF4D4F;
				border-radius: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				transition: all 0.3s ease;
				
				&:active {
					background: #fff2f0;
					transform: translateY(2rpx);
				}
				
				.btn-text {
					font-size: 32rpx;
					color: #FF4D4F;
					font-weight: 600;
				}
			}
			
			.save-btn {
				flex: 2;
				height: 100rpx;
				background: linear-gradient(135deg, #FF6B35 0%, #FE6100 100%);
				border: none;
				border-radius: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				transition: all 0.3s ease;
				
				&:active {
					transform: translateY(2rpx);
					background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
				}
				
				.btn-text {
					font-size: 32rpx;
					color: white;
					font-weight: 600;
				}
			}
		}
	}

	// 兼容旧样式
	.header_slot {
		padding: 0 32rpx;
		width: 100%;
		font-weight: 500;
		font-size: 36rpx;
		color: #2C2622;
	}

	.from_btn {
		padding: 32rpx;
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;

		.cu-btn {
			width: 100%;
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 48rpx;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
		}
	}

	switch::after,
	switch::before {
		content: '' !important;
	}

	.select_address {
		width: 70%;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 32rpx;
		color: rgba(0, 0, 0, 0.9);
		line-height: 48rpx;
		text-align: left;
	}

	.forms_box {
		background-color: #FFFFFF;
	}
</style>